import 'dart:convert';

import 'package:qunaimedical/models/qa_user.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SPUtil {
  SPUtil._internal();

  static SharedPreferences? _spf;

  static Future<SharedPreferences?> init() async {
    if (_spf == null) {
      _spf = await SharedPreferences.getInstance();
    }
    return _spf;
  }

  /// 语言
  static Future<bool> setLanguageCode(String languageCode) {
    return _spf!.setString('language_code', languageCode);
  }

  static String? getLanguageCode() {
    return _spf!.getString('language_code');
  }

  /// 首次引导
  static Future<bool> setFirst(bool first) {
    return _spf!.setBool('first', first);
  }

  static bool isFirst() {
    return _spf!.getBool('first') ?? true;
  }

  static Future<bool> setQAUser(QAUser? value) {
    if (value == null) {
      return _spf!.remove('qa_user');
    }
    return _spf!.setString('qa_user', json.encode(value.toJson()));
  }

  static QAUser? getQAUser() {
    String? value = _spf!.getString('qa_user');
    if (value == null) {
      return null;
    } else {
      return QAUser.fromJson(json.decode(value));
    }
  }

  static Future<bool> setUserName(String value) {
    return _spf!.setString('qa_userName', value);
  }

  static String? getUserName() {
    return _spf!.getString('qa_userName');
  }

  static Future<bool> setPassword(String value) {
    return _spf!.setString('qa_password', value);
  }

  static String? getPassword() {
    return _spf!.getString('qa_password');
  }

  static void logout() {
    _spf!.remove("qa_user");
    _spf!.remove("qa_userName");
    _spf!.remove("qa_password");
  }
}
